<template>

  <div>
    <el-radio-group v-model="radio_Value" @change="onRadioChange">
      <el-radio-button v-for="(item, index) of dateList" :key="index" :label="item.value">{{ item.label }}</el-radio-button>
    </el-radio-group>
    <el-date-picker
      :value="pickTimes"
      style="width:250px"
      type="daterange"
      value-format="yyyy-MM-dd"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      @input="onDateChange($event)"
    />

  </div>
</template>

<script>
import { parseTime } from '@/utils'

export default {
  name: 'BaseDateRange',
  props: {
    radioValue: {
      type: Number,
      default: 0
    },
    value: {
      type: Array,
      default: () => { return [] }
    }

  },
  data() {
    return {
      pickTimes: this.value,
      dateList: [
        { value: 0, label: '今天' },
        { value: 1, label: '昨天' },
        { value: 7, label: '近7天' },
        { value: 30, label: '近30天' }
      ],
      radio_Value: 0
    }
  },
  watch: {
    radioValue(newValue) {
      this.radio_Value = this.radioValue
      this.onRadioChange()
    }
  },
  created() {

  },
  mounted() {
    this.initDate()
    this.radio_Value = this.radioValue
  },
  methods: {
    initDate() {
      this.pickTimes = [parseTime(new Date(), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
      this.onRadioChange()
    },
    // 点击时间按钮
    onRadioChange() {
      let beginTime = ''
      let endTime = ''
      const value = this.radio_Value - 1
      switch (this.radio_Value) {
        case 0:
          beginTime = parseTime(new Date(), '{y}-{m}-{d}')
          endTime = beginTime
          break
        case 1:
          beginTime = parseTime(new Date().getTime() - 3600 * 1000 * 24 * 1, '{y}-{m}-{d}')
          endTime = beginTime
          break
        default:
          beginTime = parseTime(new Date().getTime() - 3600 * 1000 * 24 * value, '{y}-{m}-{d}')
          endTime = parseTime(new Date(), '{y}-{m}-{d}')
          break
      }
      this.pickTimes = [beginTime, endTime]
      this.onDateChange(this.pickTimes)
    },
    //  选择时间
    onDateChange(dates) {
      this.$emit('input', dates)
      this.pickTimes = dates
      this.handleChangeDate()
    },

    // 暴露给组件方法
    handleChangeDate() {
      this.$emit('handleChangeDate', this.pickTimes ? this.pickTimes : [])
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
